﻿using UnityEngine;
using System.Collections;

using XInputDotNetPure; // Required in C#


public class StartScript : MonoBehaviour {

	bool playerIndexSet = false;
	PlayerIndex playerIndex;
	GamePadState state;
	GamePadState prevState;

	public GameObject levelTextNr;

	int level = 1;

	float startTimer;

	// Use this for initialization
	void Start () 
	{
		startTimer = 0;
		FindPlayerIndex();

	}

	bool thumbPressed = false;

	void SetLevel(int newlevel)
	{
		if(newlevel < 1) newlevel = Application.levelCount-2;
		if(newlevel > Application.levelCount-2) newlevel = 1;

		level = newlevel;
		UnityEngine.UI.Text txt = (UnityEngine.UI.Text)levelTextNr.GetComponent(typeof( UnityEngine.UI.Text ));

		txt.text = "< " + level.ToString() + " >";// ' H');
		

	}
	
	void FindPlayerIndex()
	{
		// Find a PlayerIndex, for a single player game
		// Will find the first controller that is connected ans use it
		if (!playerIndexSet || !prevState.IsConnected)
		{
			for (int i = 0; i < 4; ++i)
			{
				PlayerIndex testPlayerIndex = (PlayerIndex)i;
				GamePadState testState = GamePad.GetState(testPlayerIndex);
				if (testState.IsConnected)
				{
					Debug.Log(string.Format("GamePad found {0}", testPlayerIndex));
					playerIndex = testPlayerIndex;
					playerIndexSet = true;
				}
			}
		}
		
		prevState = state;
		state = GamePad.GetState(playerIndex);
		
	}
	
	// Update is called once per frame
	void Update () 
	{
		prevState = state;
		state = GamePad.GetState(playerIndex);

		if(state.Buttons.A == ButtonState.Released){ startTimer = 10;}

		startTimer = startTimer + Time.deltaTime;
		if(startTimer < 2)
		{
			return;
		}

		if(state.Buttons.A == ButtonState.Pressed)
		{
			Application.LoadLevel(level);
		}

		//ThumbstickVecLeft.x = state.ThumbSticks.Left.X;
		//ThumbstickVecLeft.y = state.ThumbSticks.Left.Y;
		if(state.ThumbSticks.Left.X > 0.5)
		{
			if(thumbPressed != true)
			{
				SetLevel(level+1);
			}
			thumbPressed = true;
		}
		else if(state.ThumbSticks.Left.X < -0.5)
		{
			if(thumbPressed != true)
			{
			SetLevel(level-1);
			}
			thumbPressed = true;
		}
		else
		{
			thumbPressed = false;
		}


	}
}
